package com.hefan.api.controller.H5;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.DateUtils;
import com.hefan.common.oss.AliOssService;
import com.hefan.common.oss.dao.OssUploadCfgVo;
import com.hefan.common.util.DynamicProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by kevin_zhang on 01/03/2017.
 */
@Controller
@RequestMapping("/v1/h5")
public class AliOssController {
    private Logger logger = LoggerFactory.getLogger(AliOssController.class);

    @Reference
    AliOssService aliOssService;

    @Resource
    JedisService jedisService;

    private static final String ALI_UPLOAD_CONFIG_KEY = "ali_upload_config";

    /**
     * 获取阿里OSS上传所需签名，私钥
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getAliOssUploadCfg")
    @ResponseBody
    public String getLiveActivity(HttpServletRequest request) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS, null);
        try {
            long expireTime = DynamicProperties.getLong("oss.upload.config.expireTime") * 1000;
            OssUploadCfgVo vo;
            String infoRedis = jedisService.getStr(ALI_UPLOAD_CONFIG_KEY);
            if (StringUtils.isNotBlank(infoRedis)) {
                vo = JSON.parseObject(infoRedis, OssUploadCfgVo.class);
                /**
                 * 失效时间发生变化时，重新获取上传的签名信息
                 */
                if (expireTime != vo.getExpireTime()) {
                    vo = aliOssService.getOssUploadCfgInfo(expireTime);
                    jedisService.setexStr(ALI_UPLOAD_CONFIG_KEY, JSON.toJSONString(vo), ((int) vo.getExpireTime() / 1000 - 3));
                }
            } else {
                vo = aliOssService.getOssUploadCfgInfo(expireTime);
                jedisService.setexStr(ALI_UPLOAD_CONFIG_KEY, JSON.toJSONString(vo), ((int) vo.getExpireTime() / 1000 - 3));
            }
            resultBean.setData(vo);
            resultBean.setCode(ResultCode.SUCCESS.get_code());
            resultBean.setMsg(ResultCode.SUCCESS.getMsg());
            return JSON.toJSONString(resultBean);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(new ResultBean(ResultCode.UnknownException, null));
        }
    }
}
